package cn.shengchao.examstarvideo.service;

import cn.hutool.db.nosql.redis.RedisDS;
import cn.shengchao.examstarvideo.config.FileTypeEnum;
import cn.shengchao.examstarvideo.mapper.FileMapper;
import cn.shengchao.examstarvideo.mapper.po.FileDO;
import cn.shengchao.examstarvideo.util.AliVideoUploadUtil;
import com.aliyun.sdk.service.vod20170321.models.BatchGetMediaInfosResponseBody;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.continew.starter.cache.redisson.util.RedisUtils;

import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.ExecutionException;


@Service
public class VideoService {

    @Autowired
    private AliVideoUploadUtil aliVideoUploadUtil;

    @Autowired
    private FileMapper fileMapper;

    @Value("${video_url}")
    private String VIDEO_URL;

    private static final String WATCH_VIDEO_KEY = "WATCH_VIDEO_KEY:";

    public CreateUploadVideoResponse getVideoUploadAuth(String title, String fileName, String extension, Long size) throws ClientException {
        FileDO fileDO = new FileDO();
        fileDO.setName(title);
        fileDO.setExtension(extension);
        fileDO.setSize(size);
        fileDO.setType(FileTypeEnum.getByExtension(extension).getValue());
        CreateUploadVideoResponse createUploadVideoResponse = aliVideoUploadUtil.getVideoPlayAuth(title, fileName);
        String videoId = createUploadVideoResponse.getVideoId();
        fileDO.setAttr(String.format("""
                {
                   "videoId":"%s"
                }
                """, videoId));
        fileDO.setStorageId(647482339571531781L);
        fileDO.setUrl(String.format(VIDEO_URL, videoId, extension));
        fileMapper.insert(fileDO);
        return createUploadVideoResponse;
    }

    public RefreshUploadVideoResponse refreshVideoPlayAuth(String videoId) throws ExecutionException, InterruptedException, ClientException {
        return aliVideoUploadUtil.refreshVideoPlayAuth(videoId);
    }

    public String videoFile(String videoId, String definition, String videoType) throws ExecutionException, InterruptedException, ClientException {
        String url = RedisUtils.get(WATCH_VIDEO_KEY + videoId+":"+videoType);
        BatchGetMediaInfosResponseBody.MediaInfos mediaInfos;
        if (url != null) {
            return url;
        } else {
            //获取阿里云视频信息
            mediaInfos = aliVideoUploadUtil.getVideoInfo(videoId);
            if (mediaInfos != null) {
                FileDO fileDO = fileMapper.selectOne(Wrappers.lambdaQuery(FileDO.class).like(FileDO::getAttr, videoId).last("limit 1"));
                if (fileDO != null) {
                    //时长
                    fileDO.setDuration(Double.valueOf(mediaInfos.getMezzanineInfo().getDuration()));
                    //封面
                    fileDO.setThumbnailUrl(mediaInfos.getMediaInfo().getCoverURL());
                    //大小
                    fileDO.setSize(mediaInfos.getMezzanineInfo().getSize());
                    fileMapper.updateById(fileDO);
                }
            }
        }
        if (mediaInfos != null) {
            Optional<BatchGetMediaInfosResponseBody.PlayInfoList> playInfoList = mediaInfos
                    .getPlayInfoList().stream().filter(playInfo -> playInfo.getFormat().equals(videoType)).findFirst();
            if (playInfoList.isPresent()) {
                url = playInfoList.get().getPlayURL();
                RedisUtils.set(WATCH_VIDEO_KEY + videoId+":"+videoType, url, Duration.ofDays(1));
                return url;
            }
            if (mediaInfos.getMezzanineInfo() != null) {
                return mediaInfos.getMezzanineInfo().getFileURL();
            }
        }

        return "";
    }
}
